package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZPolitics;
import com.sec.etech.employeesync.mapper.OrgEmployeeZPoliticsMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class PoliticsConfigHandler implements ConfigTableHandler<OrgEmployeeZPolitics> {

    @Resource
    private OrgEmployeeZPoliticsMapper politicsMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZPolitics politics = getEntityByName(name);
        if (politics == null) {
            politics = new OrgEmployeeZPolitics();
            politics.setCode(generateNextCode());
            politics.setName(name);
            politics.setActive(1);
            insertEntity(politics);
            log.info("新增政治面貌配置:name={}", name);
        }
        return politics.getPoliticsId();
    }

    @Override
    public OrgEmployeeZPolitics getEntityByName(String name) {
        return politicsMapper.selectOne(Wrappers.<OrgEmployeeZPolitics>lambdaQuery()
                .eq(OrgEmployeeZPolitics::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZPolitics politics = politicsMapper.selectOne(Wrappers.<OrgEmployeeZPolitics>lambdaQuery()
                .orderByDesc(OrgEmployeeZPolitics::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZPolitics::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZPolitics entity) {
        politicsMapper.insert(entity);
    }
}
